package com.bw.broker.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.broker.mapper.TbHouseBrokerLiveMapper;
import com.bw.broker.service.TbHouseBrokerLiveService;
import com.bw.po.TbHouseBrokerLive;
import com.bw.result.ResponseState;
import com.bw.result.ResultVo;
import com.bw.util.TxLiveUtils;
import com.bw.vo.TbHouseLiveVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
* @author 007
* @description 针对表【tb_house_broker_live(房源经纪人直播)】的数据库操作Service实现
* @createDate 2023-11-12 21:42:24
*/
@Service
public class TbHouseBrokerLiveServiceImpl extends ServiceImpl<TbHouseBrokerLiveMapper, TbHouseBrokerLive>
    implements TbHouseBrokerLiveService {
    @Autowired
    private TbHouseBrokerLiveMapper tbHouseBrokerLiveMapper;;

    @Override
    public ResultVo liveList(TbHouseLiveVo tbHouseLiveVo) {
        //分页
        // Page<TbHouseBrokerLive> tbHouseLivePage=null;
            Page<Object> pages = new Page<>(tbHouseLiveVo.getPageNum(), tbHouseLiveVo.getPageSize());
        // Page<TbHouseBrokerLive> page = page(tbHouseLivePage);
        // QueryWrapper<TbHouseBrokerLive> wrapper = new QueryWrapper<>();
        // //经纪人姓名模糊查询
        // if (StringUtils.isNotEmpty(tbHouseLiveVo.getBrokerName())){
        //     wrapper.lambda().like(TbHouseBrokerLive::getBrokerName,tbHouseLiveVo.getBrokerName());
        // }
        // //经纪人id查询
        // if (StringUtils.isNotEmpty(tbHouseLiveVo.getBrokerId())){
        //     wrapper.lambda().eq(TbHouseBrokerLive::getBrokerId,tbHouseLiveVo.getBrokerName());
        // }
        // //直播状态查询
        // if (tbHouseLiveVo.getStatus()!=null){
        //     wrapper.lambda().eq(TbHouseBrokerLive::getStatus,tbHouseLiveVo.getStatus());
        // }
        // page.setRecords(list(wrapper));
        // 分页模糊查询
        Page<TbHouseBrokerLive> listPage= tbHouseBrokerLiveMapper.listPage(pages,tbHouseLiveVo);
        return ResultVo.SUCCESS(listPage);
    }

    @Override
    public ResultVo getLive(TbHouseLiveVo tbHouseLiveVo) {
        QueryWrapper<TbHouseBrokerLive> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(TbHouseBrokerLive::getRoomNo,tbHouseLiveVo.getRoomNo());
        TbHouseBrokerLive one = getOne(wrapper);
        if (one==null){
            return  ResultVo.FAILED(ResponseState.LIVE_NOT_EXIST);
        }
        TbHouseLiveVo houseLiveVo = new TbHouseLiveVo();
        BeanUtils.copyProperties(one,tbHouseLiveVo);
        return ResultVo.SUCCESS(tbHouseLiveVo);
    }

    @Override
    public ResultVo add(TbHouseLiveVo tbHouseLiveVo) {
        //@TODD 直播房间号自动生成 唯一标识
        UUID uuid = UUID.randomUUID();
        //判断直播间房号是否重复
        TbHouseBrokerLive one = getOne(
                new QueryWrapper<TbHouseBrokerLive>().lambda().eq(TbHouseBrokerLive::getRoomNo, tbHouseLiveVo.getRoomNo()).last("limit 1")
        );
        if (one!=null){
            return  ResultVo.FAILED(ResponseState.LIVE_EXIST);
        }
        //添加
        TbHouseBrokerLive tbHouseBrokerLive = new TbHouseBrokerLive();
        tbHouseBrokerLive.setRoomNo(uuid.toString());
        BeanUtils.copyProperties(tbHouseLiveVo,tbHouseBrokerLive);

        //开始时间
        Date date = new Date();
        tbHouseBrokerLive.setLiveStartTime(date);

        //结束时间(自动按当前时间向后延一天)
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, 1);
        Date endTime = cal.getTime();
        tbHouseBrokerLive.setLiveEndTime(endTime);

        //生成推流地址
        String pushUrl = TxLiveUtils.makePushUrl(tbHouseLiveVo.getStreamName(), endTime);
        //生成拉流地址
        String playUrl = TxLiveUtils.makePlayUrl(tbHouseLiveVo.getStreamName());
        tbHouseBrokerLive.setPushPath(pushUrl);
        tbHouseBrokerLive.setPullPath(playUrl);

        //添加直播间
        boolean save = save(tbHouseBrokerLive);
        return save?ResultVo.SUCCESS():ResultVo.FAILED(ResponseState.INSERT_ERROR);
    }

    @Override
    public ResultVo deleteLive(TbHouseLiveVo tbHouseLiveVo) {
        QueryWrapper<TbHouseBrokerLive> wrapper = new QueryWrapper<>();

        if (tbHouseLiveVo.getRoomNo()==null){
            return ResultVo.FAILED(ResponseState.LIVE_NOT_EXIST);
        }
        wrapper.lambda().eq(TbHouseBrokerLive::getRoomNo,tbHouseLiveVo.getRoomNo());

        boolean remove = remove(wrapper);
        return remove?ResultVo.SUCCESS():ResultVo.FAILED(ResponseState.DELETE_ERROR);
    }

    @Override
    public ResultVo updateLive(TbHouseLiveVo tbHouseLiveVo) {
        TbHouseBrokerLive tbHouseBrokerLive = new TbHouseBrokerLive();
        BeanUtils.copyProperties(tbHouseLiveVo,tbHouseBrokerLive);
        boolean updateLive = updateById(tbHouseBrokerLive);
        return updateLive?ResultVo.SUCCESS():ResultVo.FAILED(ResponseState.UPDATE_ERROR);
    }

    @Override
    public ResultVo openCloudRecording(TbHouseLiveVo tbHouseLiveVo) {
        //调用封装方法打开录制
        String s = TxLiveUtils.openCloudRecording(tbHouseLiveVo.getBrokerId(), tbHouseLiveVo.getRoomNo());
        return ResultVo.SUCCESS(s);
    }

    @Override
    public ResultVo closeDeleteCloudRecording(String taskId) {
        //带哦永丰庄磊关闭直播
        String s = TxLiveUtils.closeDeleteCloudRecording(taskId);
        return ResultVo.SUCCESS(s);
    }

    @Override
    public ResultVo recordingCallback(String body, HttpServletRequest request) throws Exception {
        String key="key";
        String sdkAppId=request.getHeader("SdkAppId");
        String sign = request.getHeader("Sign");
        String resultSign = TxLiveUtils.getResultSign(key, body);
        if (resultSign.equals(sign)){
            JSONObject jsonObject= (JSONObject) JSON.parse(body);
            //事件类型
            Integer eventType = jsonObject.getInteger("EventType");
            //事件信息
            String eventInfo = jsonObject.getString("EventInfo");
            //任务ID
            JSONObject jsonObject1= (JSONObject) JSON.parse(eventInfo);
            //根据不同事件类型定义不同
            String taskId = jsonObject1.getString("TaskId");
            String payLoad = jsonObject1.getString("PayLoad");
            JSONObject jsonObject2= (JSONObject) JSON.parse(payLoad);
            //点播平台信息
            String tencentVod = jsonObject2.getString("TencentVod");
            JSONObject jsonObject3= (JSONObject) JSON.parse(tencentVod);
            if (eventType==311){//录制视频上传成功
                //点播平台唯一 ID
                String fileId = jsonObject3.getString("FileId");
                //点播平台播放地址
                String videoUrl = jsonObject3.getString("VideoUrl");
                //UI业务进行逻辑处理
                //311事件证明现在已经上传到云点播
                //建立相关的数据库用来存储音视频录制地址和相关的业务ID绑定,便于以后下载
                String [] fileIds={fileId};
                /**
                 * 使用线程池进行音视频下载 控制最大并发数 防止资源抢夺导致死锁
                 */
                ExecutorService executorService = Executors.newCachedThreadPool();
                executorService.submit(()->{
                    try {
                        TxLiveUtils.downloadVideo(fileIds);
                        //等待三十分钟
                        TimeUnit.SECONDS.sleep(1000*60*30);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
            }else{
                System.out.println("{'Status': 'FAIL', 'Info': '校验失败'}");
                return  ResultVo.FAILED(ResponseState.LIVE_CALL_BACK_ERROR);
            }

        }
        return ResultVo.SUCCESS();
    }

    @Override
    public ResultVo recordingCall(String body, HttpServletRequest request) throws Exception {
        String key="key";
        String sdkAppId=request.getHeader("SdkAppId");
        String sign = request.getHeader("Sign");
        String resultSign = TxLiveUtils.getResultSign(key, body);
        JSONObject jsonObject3=null;
        if (resultSign.equals(sign)){
            JSONObject jsonObject= (JSONObject) JSON.parse(body);
            //事件类型
            Integer eventType = jsonObject.getInteger("EventType");
            //事件信息
            String eventInfo = jsonObject.getString("EventInfo");
            //任务ID
            JSONObject jsonObject1= (JSONObject) JSON.parse(eventInfo);
            //根据不同事件类型定义不同
            String taskId = jsonObject1.getString("TaskId");
            String payLoad = jsonObject1.getString("PayLoad");
            JSONObject jsonObject2= (JSONObject) JSON.parse(payLoad);
            //点播平台信息
            String tencentVod = jsonObject2.getString("TencentVod");
            jsonObject3= (JSONObject) JSON.parse(tencentVod);
            if (eventType!=311){//录制视频上传成功
                System.out.println("{'Status': 'FAIL', 'Info': '校验失败'}");
                return  ResultVo.FAILED(ResponseState.LIVE_CALL_BACK_ERROR);
            }
        }
        //点播平台唯一 ID
        String fileId = jsonObject3.getString("FileId");
        //点播平台播放地址
        String videoUrl = jsonObject3.getString("VideoUrl");
        return ResultVo.SUCCESS(videoUrl);
    }


}




